#!/usr/bin/env python3
# coding:utf-8

import os
import sys
import argparse
import ast

sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)),'../'))
from ocs_ci_api.utils.ocs_db import get_all_packages, get_package_by_name
from ocs_ci_api.models.git_api.gitee_api import GiteeAPI as git
from ocs_ci_api.output.logger import setup_logger

logger = setup_logger("Update Maintainer", log_file = "Update_Maintainer.log")

special_username = ['rockerzhu', 'nilusyi', 'ocs-bot']
special_repo_name = ['rpm-check', 'rpm-upgrade', 'rpm-dep']


def get_maintainer(git_api, name, group):
    ret = {}
    maintainer_infos = git_api.get_repo_collaborator(name, group)
    for i in range(len(maintainer_infos)):
        username = maintainer_infos[i].login    
        permissions = ast.literal_eval(maintainer_infos[i].permissions)
        if permissions['admin']:
            ret[username] = 'admin'
        elif permissions['push']:
            ret[username] = 'push'
        elif permissions['pull']:
            ret[username] = ['pull']
        else:
            logger.warning(f"can not get {group}/{name} repo {username} user permission, info = {maintainer_infos[i]}")
    return ret


def main(token):
    group="opencloudos-stream"
    git_api = git(token)
    page_num = 1

    while True:
        try:
            status_code, json = get_all_packages(page=page_num, per_page=10)
            page_info = json['packages']
            if not page_info:
                logger.info(f"page num = {page_num}, status_code = {status_code}, exit!")
                break
        except Exception as e:
            logger.warning(f"{e}")

        for i in range(len(page_info)):
            repo = None
            try:
                info = json['packages'][i]
                repo = info['package_name']

                if repo in special_repo_name:
                    logger.info(f"do not update special repo {repo} maintainer")
                    continue
                if info['repo_url'] is None:
                    logger.warning(f"[{repo}] url is None")
                    continue
                if info['first_maintainer'] is None:
                    logger.debug(f"[{repo}] first_maintainer is None")
                    continue

                # if not special name and not maintainer, remove
                cur_maintainer = get_maintainer(git_api, repo, group)
                db_maintainer = []
                if info['first_maintainer']:
                    db_maintainer.append(info['first_maintainer'])
                if info['second_maintainer']:
                    db_maintainer.append(info['second_maintainer'])

                for maintainer in cur_maintainer:
                    if maintainer in special_username or maintainer in db_maintainer:
                        continue
                    git_api.delete_repo_collaborator(repo, group, maintainer)
                    logger.info(f"[{repo}] Deleting: {maintainer}")

                for maintainer in db_maintainer:
                    if maintainer in cur_maintainer:
                        continue
                    git_api.add_repo_collaborator(repo, group, maintainer, "push")
                    logger.info(f"[{repo}] Adding: {maintainer}")
            except Exception as e:
                logger.error(f"[{repo}] {e}", exc_info=True)
        page_num += 1



if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='add maintainer for all repo')
    parser.add_argument('--token', type=str, required=True, help='git access token')
    args = parser.parse_args()

    main(args.token)
